package com.slipper.groovy.writer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Writer;

public class PrintWriter {
    private final Logger logger = LoggerFactory.getLogger("logger");

    private final String prefix;
    private final Writer writer;

    public PrintWriter(String scriptName, Writer writer) {
        this.prefix = scriptName == null ? "" : ("执行脚本【" + scriptName + "】：");
        this.writer = writer;
    }

    public void print(Object object) {
        if (object == null) return;

        if (writer != null) {
            try {
                writer.write(object.toString());
            } catch (Exception ignored) {}
        }

        logger.info("{}{}", this.prefix, object);
    }

    public void println(Exception e) {
        if (e == null) return;

        if (writer != null) {
            e.printStackTrace(new java.io.PrintWriter(writer));
        }

        logger.error("脚本运行异常！", e);
    }

    public void println(Object object) {
        if (object == null) return;

        if (writer != null) {
            try {
                writer.write(object.toString());
                writer.write('\n');
            } catch (Exception ignored) {}
        }

        logger.info("{}{}", this.prefix, object);
    }

    public String toString() {
        return writer == null ? null : writer.toString();
    }
}
